<template>
  <div class="legal-advice-container">
    <QuestionsAnswers
      :robotInfo="robotInfo"
      :chatRecord="chatRecord"
      :qaBankTypes="qaBankTypes"
      :randomNum="randomNum"
      :presetKeyWordsData="presetKeyWordsData"
      @handleQaBankType="handleQaBankType"
      @handleListQuery="handleListQuery"
      @handleMoreQueName="handleMoreQueName"
      @handleComplianceChecklist="handleComplianceChecklist"
    />
    <Footer @handleSendQuestion="handleSendQuestion" />
    <div class="suggestions-btn" @click="handleSuggestions">
      <div class="suggestions-logo"></div>
      <div class="suggestions-text">意见建议</div>
    </div>
    <div ref="wantHide" style="display: none"></div>
  </div>
</template>

<script>
import QuestionsAnswers from "./QuestionsAnswers";
import Footer from "./Footer";
import dayjs from "dayjs";
import {
  getRobotInfo,
  getUserInfo,
  getTalkAnswers,
  getMineRelationQueName,
  getPresetKeyWordsTypes,
} from "@/api";
import { Toast, getTalkSessionId, slidingScrollBar } from "@/utils";

//问答类型
const QA_TYPE_3 = 3,
  QA_TYPE_6 = 6;

//问答容器类名
const QA_CON = ".questions-answers-container";

export default {
  name: "LegalAdviceIndex",
  components: {
    QuestionsAnswers,
    Footer,
  },
  data() {
    return {
      inpValue: "", //输入框内容
      robotInfo: {}, //机器人信息
      chatRecord: [], //聊天记录
      randomNum: 3, //随机抽取的数量和列表默认显示的数量
      qaBankTypes: {
        //风险图谱题库
        riskAtlas: {
          label: "riskAtlas",
          name: "我要了解合规职责",
          alias: "合规职责",
          textLen: 150,
        },
        //合规指引题库
        complianceAdvice: {
          label: "complianceAdvice",
          name: "我要咨询",
          alias: "咨询",
          textLen: 250,
        },
      },
      currentQaBankType: {}, //当前题库类型
      mineRelationQueName: [], //关联的岗位的风险点
      presetKeyWordsData: [], //预设关键字
    };
  },
  created() {
    //获取机器人信息
    this.getRobotInfoData();

    //获取用户信息
    this.getUserInfoData();

    //获取预设信息
    this.getPresetKeyWords();

    //获取与我关联的岗位的风险点数据
    this.getMineRelationData();
  },
  mounted() {
    //设置题库类型
    this.currentQaBankType = this.qaBankTypes.complianceAdvice;

    //发送开场语
    this.chatRecord.push({
      type: "receive_0",
      data: null,
      time: this.getTime(),
    });
  },
  methods: {
    /**
     * 跳转到意见建议页面
     */
    handleSuggestions() {
      this.$router.push({ name: "OpinionsSuggestions" });
    },

    /**
     * 获取机器人信息
     */
    async getRobotInfoData() {
      this.robotInfo = (await getRobotInfo()) || {};
      localStorage.setItem("robotInfo", JSON.stringify(this.robotInfo));
    },

    /**
     * 获取用户信息
     */
    async getUserInfoData() {
      const userInfo = (await getUserInfo()) || {};
      localStorage.setItem("userInfo", JSON.stringify(userInfo));
    },

    /**
     * 获取与我关联的岗位的风险点数据
     */
    async getMineRelationData() {
      this.mineRelationQueName = await getMineRelationQueName();
    },

    /**
     * 获取预设关键字数据
     */
    async getPresetKeyWords() {
      this.presetKeyWordsData = await getPresetKeyWordsTypes();
    },

    /**
     * 用户输入内容
     */
    handleSendQuestion(value) {
      this.inpValue = value;
      this.getTalkAnswersData();
    },

    /**
     * 获取用户查询内容
     */
    async getTalkAnswersData({
      level = 0,
      areas = "",
      bankNo = "",
      qaBankType = this.currentQaBankType,
    } = {}) {
      try {
        Toast.startLoading();

        //发送聊天记录
        this.chatRecord.push({
          type: "send",
          data: this.inpValue,
          time: this.getTime(),
        });

        //查询数据
        const { data = [], nextLevel = 0 } = await getTalkAnswers({
          type: 1,
          queName: this.inpValue,
          qaBankType: qaBankType.label,
          level,
          areas,
          bankNo,
          robotName: this.robotInfo.robotName,
          talkSessionId: getTalkSessionId(),
        });

        //显示的列表数据量
        const newData = data.slice(0, this.randomNum);
        this.moreQueModule(nextLevel, newData);

        //处理显示文本
        nextLevel === QA_TYPE_6 && this.displaySectionData(data);

        //发送聊天记录
        this.chatRecord.push({
          type: "receive_1",
          level: nextLevel,
          queName: this.inpValue,
          data: newData,
          responseData: data,
          qaBankType,
        });
      } catch (err) {
        this.chatRecord.push({
          type: "receive_1",
          queName: this.inpValue,
        });
      } finally {
        this.$nextTick(this.focusAnswer);

        Toast.closeLoading();
      }
    },

    /**
     * 点击更多问题题干
     * @param {*} $event 事件对象
     * @param {*} record 机器人聊天回答数据
     */
    handleMoreQueName({ $event, record }) {
      //截取显示的数据
      record.data = record.responseData.slice(
        0,
        record.data.length + this.randomNum
      );

      this.moreQueModule(record.level, record.data);

      //获取元素原始高度
      const originHeight = $($event.target).parents(".robot-text").height();

      this.$nextTick(() => {
        const height =
          $($event.target).parents(".robot-text").height() - originHeight;

        //点击后滚动一段距离
        slidingScrollBar(QA_CON, $(QA_CON).scrollTop() + height);
      });
    },

    /**
     * 问题模块特殊处理
     * @param {*} level 类型
     * @param {*} data 聊天数据
     */
    moreQueModule(level, data) {
      if (level === QA_TYPE_3) {
        data.forEach((answer) => {
          answer.contents = answer.contents || [answer.content];
          answer.showContents = answer.contents.slice(
            0,
            (answer.showContents?.length || 0) + this.randomNum
          );
        });
      }
    },

    /**
     * 点击题库类型
     * @param {*} qaBankType 类型
     */
    handleQaBankType(qaBankType) {
      //保存当前点击的类型
      this.currentQaBankType = qaBankType;

      // 发送聊天记录
      this.chatRecord.push({
        type: "send",
        data: qaBankType.name,
        time: this.getTime(),
      });

      //是否点击的是风险图谱题库
      if (qaBankType === this.qaBankTypes.riskAtlas) {
        //随机几条数据显示
        const randomArray = this.getRandomArrayValue(
          this.mineRelationQueName,
          this.randomNum
        );

        //机器人回答
        this.chatRecord.push({
          type: "receive_2",
          queName: qaBankType.name,
          qaBankType: qaBankType,
          data: randomArray,
        });
        this.chatRecord.push({
          type: "receive_3",
        });
      } else {
        this.chatRecord.push({
          type: "receive_4",
        });
      }
      this.$nextTick(this.focusAnswer);
    },

    /**
     * 列表数据查询
     * @param {*} obj 参数对象
     */
    handleListQuery(obj) {
      this.inpValue = obj.queName;
      this.getTalkAnswersData(obj);
    },

    /**
     * 合规职责清单
     * @param {*} name 名称
     */
    handleComplianceChecklist(name) {
      // 发送聊天记录
      this.chatRecord.push({
        type: "send",
        data: name,
        time: this.getTime(),
      });

      this.chatRecord.push({
        type: "receive",
        data: "请到PC端查看合规职责清单",
      });

      this.$nextTick(this.focusAnswer);
    },

    /**
     * 获取数组中随机的数据
     * @param {*} arr 数组
     * @param {*} num 取几个数
     */
    getRandomArrayValue(arr, num) {
      //新建一个数组，不直接操作传入的数组;
      const tempArray = arr;

      if (tempArray.length <= num) {
        return tempArray;
      }

      return tempArray.splice(0, num);
    },

    /**
     * 数据过长显示部分数据
     * @param {*} data 聊天数据
     */
    displaySectionData(data) {
      //题库数据解构
      const {
        riskAtlas: { textLen: riskTextLen },
        complianceAdvice: { textLen: complianceTextLen },
      } = this.qaBankTypes;

      data.forEach((answer) => {
        const { riskWarning, respContent, questionAnswer } = answer || {};

        //合规义务
        answer.hiddenOverRiskWarning = this.wantHideData(
          riskWarning,
          riskTextLen
        );

        //违规责任
        answer.hiddenOverRespContent = this.wantHideData(
          respContent,
          riskTextLen
        );

        //其它
        answer.hiddenOverQuestionAnswer = this.wantHideData(
          questionAnswer,
          complianceTextLen
        );
      });
    },

    /**
     * 判断数据文本是否大于定义的长度，往隐藏标签中填充html，再取数其中的文本
     * @param {*} html 标签数据
     * @param {*} len 长度
     */
    wantHideData(html, len) {
      const $dom = this.$refs.wantHide;
      $dom.innerHTML = html;
      const isOver = $dom.innerText.length > len;
      $dom.innerHTML = "";
      return isOver;
    },

    /**
     * 滚动到提问气泡处
     */
    focusAnswer() {
      //获取板块中用户提问元素
      const questionsDomList = document.querySelectorAll(
        `${QA_CON} .questions`
      );

      //获取最后一个用户提问元素
      const questionsDom =
        Array.from(questionsDomList)[questionsDomList.length - 1];

      //获取该元素距离顶部的距离
      const questionsDomOffsetTop = questionsDom
        ? questionsDom.offsetTop + 20
        : 0;

      //滚动
      slidingScrollBar(QA_CON, questionsDomOffsetTop);
    },

    /**
     * 获取当前日期时间
     */
    getTime() {
      return dayjs().format("YYYY年MM月DD日 HH:mm:ss");
    },
  },
};
</script>

<style lang="less" scoped>
@import url("~@/assets/styles/legalAdvice/index.less");
</style>